package com.team.app.controller;


import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.team.app.model.Auth;
import com.team.app.model.Company;
import com.team.app.model.Employee;
import com.team.app.service.AuthService;
import com.team.app.service.CityService;
import com.team.app.service.CompanyService;
import com.team.app.service.EmployeeService;
import com.team.app.util.BeanUtil;
import com.team.app.util.ConvertUtil;
import com.team.app.util.FormatUtil;


/**
 * Handles requests for the application home page.
 */
@Controller
public class CompanyController extends AbstractController<Company>{

	private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);
    private final String PATH_BASE="/company";
	
    //-----------------------------------------------------------------------------------
    @Autowired
    private CompanyService companyService;
    @Autowired	
	private AuthService authService;
    @Autowired	
	private CityService cityService;
    
    @Autowired	
	private EmployeeService employeeService;
    
    private Company comp;
       
    @Override
	@RequestMapping(value = PATH_BASE, method = {RequestMethod.GET, RequestMethod.POST})
	public String indexAction(Model model,HttpSession s,Company obj) {	
    	logger.info("CompanyController index");    	
    	if(!checkView(s, PATH_BASE)){
    		return accessDenied();
    	}   	
    	obj = obj!=null ? obj : new Company();
    	model.addAttribute("obj", obj);    	
    	model.addAttribute("objs", companyService.findAll(obj));   		
		return PATH_BASE+"/index";
	}

    @Override
	@RequestMapping(value = PATH_BASE+"/add", method = {RequestMethod.GET, RequestMethod.POST})
	public String addAction(Model model,HttpSession s) {
		// TODO Auto-generated method stub
    	if(!checkAdd(s, PATH_BASE)){
    		return accessDenied();
    	} 
    	comp = new Company();
		model.addAttribute("obj",comp);	
		model.addAttribute("cities", cityService.findAll());		 
		return PATH_BASE+"/input";		
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/edit/{id}", method = {RequestMethod.GET, RequestMethod.POST})
	public String editAction(Model model,HttpSession s ,@PathVariable("id")Long id) {
		// TODO Auto-generated method stub
		if(!checkEdit(s, PATH_BASE)){
			return accessDenied();
    	} 
		comp = companyService.find(id);
		model.addAttribute("obj", comp);		
		model.addAttribute("cities", cityService.findAll()); 
		return PATH_BASE+"/input";
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/confirm", method = {RequestMethod.GET, RequestMethod.POST})
	public String confirmAction(Model model,HttpSession s,@ModelAttribute("obj")Company obj ,BindingResult result) {
		// TODO Auto-generated method stub
		boolean excute = true;
		if(ConvertUtil.isEmplty(obj.getCompanyEmail())){
			setMessage(model,result,"companyEmail", "comp.email.blank");	
			excute = false;	
		}else{
			if(!FormatUtil.isEmail(obj.getCompanyEmail())){
				setMessage(model,result,"companyEmail", "comp.email.invalid");	
				excute = false;	
			}
		}
		if(ConvertUtil.isEmplty(obj.getCompanyName())){
			setMessage(model,result,"companyName", "comp.name.blank");	
			excute = false;	
		}
		if(ConvertUtil.isEmplty(obj.getCompanyPhone())){
			setMessage(model,result,"companyPhone", "comp.phone.blank");	
			excute = false;	
		}else{
			if(!FormatUtil.isPhone(obj.getCompanyPhone())){
				setMessage(model,result,"companyPhone", "comp.phone.invalid");	
				excute = false;	
			}
		}
		
		if(ConvertUtil.isNull(obj.getCompanyId()) || !ConvertUtil.isEqual(comp.getCompanyEmail(), obj.getCompanyEmail())){
			if(companyService.existEmail(obj.getCompanyEmail())){
				setMessage(model,result,"companyEmail", "comp.email.exist");	
				excute = false;	
			}
		}
		
		if(!excute){
			model.addAttribute("obj", obj);	
			model.addAttribute("cities", cityService.findAll());
			return PATH_BASE+"/input";
		}else{
			obj.setCityId(cityService.find(obj.getCityId().getCityId()));
			model.addAttribute("obj", obj );
			return PATH_BASE+"/confirm";
		}		
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/complete", method = {RequestMethod.GET, RequestMethod.POST})
	public String completeAction(Model model,HttpSession s, Company obj,BindingResult result) {
		// TODO Auto-generated method stub
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");	
		if(!ConvertUtil.isNull(comp.getCompanyId())){	
			BeanUtil.copy(obj,comp);	
			companyService.edit(comp);
			if(authService.find(obj.getCompanyEmail()) == null){				
				Auth auth = new Auth();
				auth.setCompanyId(obj.getCompanyId());
				authService.create(auth, obj, loginAuth);
			}
			model.addAttribute("obj", comp); 
		}else{		
			Auth auth = new Auth();
			Long id = companyService.create(obj);
			auth.setCompanyId(id);
			authService.create(auth, obj, loginAuth);	
			model.addAttribute("obj", obj); 
		}		
		return "redirect:"+PATH_BASE;
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/delete/{id}" ,method = {RequestMethod.GET, RequestMethod.POST})
	public String deleteAction(Model model,HttpSession s,@PathVariable("id")Long id) {	
		// TODO Auto-generated method stub
		if(!checkDelete(s, PATH_BASE)){
			return accessDenied();
    	} 
		
		comp = companyService.find(id);
		List<Auth> authList = authService.findByCompanyAll(comp.getCompanyId());
		for(Auth authComp : authList){
			authService.remove(authComp);
		}
		
		List<Employee> empList =employeeService.findAll(comp.getCompanyId());
		
		for(Employee empComp : empList){
			employeeService.remove(empComp);
		}
		
		companyService.remove(comp);		
		return "redirect:"+PATH_BASE;
	}

	@Override
	@RequestMapping(value = PATH_BASE+"/back", method = {RequestMethod.GET, RequestMethod.POST})
	public String backAction(Model model, HttpSession s, Company obj) {
		// TODO Auto-generated method stub
		
		model.addAttribute("obj", obj);		
		model.addAttribute("cities", cityService.findAll());		
		return PATH_BASE+"/input";
	}
	
	
	
}
